import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { In } from "typeorm";
import { AccessService } from "../../access/service/access.service";
import { RoleDto } from "../../role/dto/role.dto";
import { Role } from "../../role/entities/role.entity";
import { UserRole } from "../../role/entities/user-role.entity";
import { UserDto } from "../dto/user.dto";
import { User } from "../entities/user.entity";

@Injectable()
export class UserService {


    async create(user) {
        const u = await User.findOne({ where: { username: user.username } });

        if (u) {
            throw new HttpException({
                message: 'Input data validation failed',
                error: 'name must be unique',
            },
                HttpStatus.BAD_REQUEST);
        }
        return await User.save(user);

    }

    async findOne(username: string) {
        const user = await User.findOne({ where: { username: username } });
        const userRole = await UserRole.find({ where: { id: user.id } });
        const userRoleIds = userRole.map((c) => c.roleId);
        const role = await Role.find({ where: { id: In(userRoleIds) } });
        const userDto = new UserDto();
        userDto.id = user.id;
        userDto.username = user.username;
        userDto.password = user.password;
        // console.log(role);
        for (let i = 0; i < role.length; i++) {

            userDto.roles.push({ roleName: role[i].roleName });
        }

        return userDto;

    }


}